import { defineStore } from 'pinia'

export class FileListDetail {
  fileUid?: string
  detail?: Preview
}

export class Preview {
  uid?: string
  title?: string
  fullPath?: string
  suffix?: string
}

export class TabVditor {
  uid?: string
  vditor?: any
}

// 预览store，包含当前预览的文件now，与tab打开的文件列表fileList
export const usePreviewStore = defineStore('preview', {
  state: () => {
    return {
      now: {} as Preview,
      fileList: [] as FileListDetail[],
    }
  },
  getters: {
    nowFile: state => state.now,
    fileLis: state => state.fileList,
  },
  actions: {
    previewNew(uid: string, title: string, path: string, suffix: string) {
      console.log('previewStore.previewNew=>', uid, title)
      if (uid == this.now.uid) {
        console.log('previewStore.previewNew=>now already exists')
        return
      }
      const preview = new Preview()
      preview.uid = uid
      preview.title = title
      preview.fullPath = path
      preview.suffix = suffix
      this.now = preview
      const find = this.fileList.some(obj => obj.fileUid == uid)
      if (find) {
        console.log('previewStore.previewNew=>already exists=>', uid, title)
        return
      }
      const fileDetail: FileListDetail = {
        fileUid: uid,
        detail: preview,
      }
      this.fileList.push(fileDetail)
    },
    changeNow(uid: string) {
      console.log('previewStore.changeNow=>', uid)
      const now = this.fileList.filter(obj => obj.fileUid == uid)
      if (now && now[0]) {
        console.log('previewStore.changeNow=>success=>', uid)
        this.now = now[0].detail!
        return this.now
      }
      else {
        console.log('previewStore.changeNow=>false=>', uid)
        this.now = new Preview()
      }
    },
    removeOne(uid: string): number {
      console.log('previewStore.removeOne=>', uid)
      if (this.now.uid == uid) {
        console.log('previewStore.removeOne=>now clean=>', uid)
        this.now = new Preview()
      }
      let removedIndices: number = -1
      for (let i = this.fileList.length - 1; i >= 0; i--) {
        if (this.fileList[i].fileUid === uid) {
          // 使用splice删除元素，并获取删除的元素数量（这里总是1）
          this.fileList.splice(i, 1)
          console.log('previewStore.removeOne=>success=>', i)
          removedIndices = i
        }
      }
      return removedIndices
    },
    clear() {
      this.fileList.length = 0
    },
  },
})
